<?php

declare (strict_types=1);

namespace app\controller\backend;

use think\facade\Db;

class SeoCheckController extends BaseController
{
    public function index()
    {
        $limit = input('param.limit');
        $where = [];

        $list = Db::name('seo_check_task')->where($where)->order('create_time desc')->paginate($limit);

        return json(pageReturn(['code' => 0, 'data' => $list, 'msg' => lang('成功')]));
    }

    public function check()
    {
        $param = $this->request->param();
        if ($param['flag'] == 'progress') {

            $taskDetail = Db::name('seo_check_task_detail')->where('task_id', $param['task_id'])->select();
            $isEnd = true;
            $checkData = [];
            $success = 0;
            $error = 0;
            foreach ($taskDetail as $vo) {
                if ($vo['status'] == 1) {
                    $isEnd = false;
                }

                if (!empty($vo['remark'])) {
                    $data = json_decode($vo['remark'], true);
                    $checkData[] = $data;

                    if ($data['code'] == 101) {
                        foreach ($data['data'] as $key => $v) {
                            if ($v['status'] == 1) {
                                $success++;
                                continue;
                            }
                            if ($key == 'tags') {
                                $error += isset($v['msg']['ajax']) ? count($v['msg']['ajax']) : 0;
                                $error += isset($v['msg']['alt']) ? count($v['msg']['alt']) : 0;
                                continue;
                            }
                            if (is_array($v['msg'])) {
                                $error += count($v['msg']);
                            } else {
                                $error ++;
                            }
                        }
                    }

                    if ($data['code'] == 102) {
                        if ($data['data']['status'] == 1) {
                            $success++;
                        } else {
                            $error++;
                        }
                    }

                    if ($data['code'] == 103) {
                        $error += isset($data['data']['deadLink']) ? count($data['data']['deadLink']) : 0;
                        $error += isset($data['data']['keywords']) ? count($data['data']['keywords']) : 0;
                    }

                    if ($data['code'] == 104) {
                        if (isset($data['data']['inlinks']['linksHave'])) {
                            foreach ($data['data']['inlinks']['linksHave'] as $v) {
                                if ($v['status'] == 1) {
                                    $success++;
                                } else {
                                    $error++;
                                }
                            }
                        }
                        if (isset($data['data']['inlinks']['nofollow'])) {
                            foreach ($data['data']['inlinks']['nofollow'] as $v) {
                                if ($v['status'] == 1) {
                                    $success++;
                                } else {
                                    $error++;
                                }
                            }
                        }
                        if (isset($data['data']['outlinks']['linksHave'])) {
                            foreach ($data['data']['outlinks']['linksHave'] as $v) {
                                if ($v['status'] == 1) {
                                    $success++;
                                } else {
                                    $error++;
                                }
                            }
                        }
                    }
                }
            }

            if ($isEnd) {
                Db::name('seo_check_task')->where('id', $param['task_id'])->update([
                    'status' => 2,
                    'update_time' => date('Y-m-d H:i:s')
                ]);
            }

            return json(['code' => 0, 'data' => [
                'success' => $success,
                'error' => $error,
                'check_data' => $checkData,
                'is_end' => $isEnd,
                'task' => Db::name('seo_check_task')->where('id', $param['task_id'])->find()
            ], 'msg' => 'success']);
        }

        $websiteId = input('param.website_id');
        $list = Db::name('theme')->field('lang,theme')->where('is_active', 1)->where('website_id', $websiteId)->select();

        return jsonReturn(0, 'success', $list);
    }

    public function start()
    {
        if (request()->isPost()) {

            $param = input('post.');

            $hasRun = Db::name('seo_check_task')->field('id')->where('website_id', $param['website_id'])->where('status', 1)->find();
            if (!empty($hasRun)) {
                return jsonReturn(-1, lang('该站点正在检测中'));
            }

            Db::startTrans();
            try {

                $taskId = Db::name('seo_check_task')->insertGetId([
                    'website_id' => $param['website_id'],
                    'website_url' => $param['website_url'],
                    'lang' => $param['lang'],
                    'theme' => $param['theme'],
                    'status' => 1,
                    'create_time' => date('Y-m-d H:i:s')
                ]);

                $params = [
                    [
                        'task_id' => $taskId,
                        'status' => 1,
                        'code' => 'code',
                        'create_time' => date('Y-m-d H:i:s')
                    ],
                    [
                        'task_id' => $taskId,
                        'status' => 1,
                        'code' => 'web',
                        'create_time' => date('Y-m-d H:i:s')
                    ],
                    [
                        'task_id' => $taskId,
                        'status' => 1,
                        'code' => 'keywords',
                        'create_time' => date('Y-m-d H:i:s')
                    ],
                    [
                        'task_id' => $taskId,
                        'status' => 1,
                        'code' => 'links',
                        'create_time' => date('Y-m-d H:i:s')
                    ],
                    [
                        'task_id' => $taskId,
                        'status' => 1,
                        'code' => 'article',
                        'create_time' => date('Y-m-d H:i:s')
                    ],
                ];

                Db::name('seo_check_task_detail')->insertAll($params);

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return jsonReturn(-2, $e->getMessage());
            }

            $taskData = [
                'task_id' => $taskId,
                'websiteId' => $param['website_id'],
                'start_time' => date('Y-m-d H:i:s'),
                'lang' => $param['lang'],
                'theme' => $param['theme'],
                'websiteUrl' => $param['website_url'],
                'cate' => Db::name('category')->field('id,title,alias')->where('status', 1)
                    ->where('lang', $param['lang'])
                    ->where('type', '<>', 3)->where('website_id', $param['website_id'])->select(),
                'keywords' => Db::name('keyword')->field('name')->where('is_del', 1)->where('website_id', $param['website_id'])->select()
            ];

            // 以text协议发送$task_data数据
            $taskData['cmd'] = 'code';
            $this->sendData($taskData);
            $taskData['cmd'] = 'web';
            $this->sendData($taskData);
            $taskData['cmd'] = 'keywords';
            $this->sendData($taskData);
            $taskData['cmd'] = 'links';
            $this->sendData($taskData);
            $taskData['cmd'] = 'article';
            $this->sendData($taskData);

            return jsonReturn(0, lang('启动成功'), $taskData);
        }
    }

    public function del()
    {

        if (!request()->isPost()) {
            return jsonReturn(-1, lang('请求错误'));
        }

        $param = $this->request->only(['id']);

        Db::name('seo_check_task')->where('id', '=', $param['id'])->delete();
        Db::name('seo_check_task_detail')->where('task_id', '=', $param['id'])->delete();

        return jsonReturn(0, lang('删除成功'));
    }

    protected function sendData($data)
    {
        // 与服务端建立连接
        $client = stream_socket_client('tcp://127.0.0.1:19890');
        fwrite($client, json_encode($data) . "\n");
        //关闭句柄
        fclose($client);
    }
}
